﻿using System;
using System.ComponentModel;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using EIIS.Infrastructure.Service.Business;
using EIIS.Infrastructure.Service.System;
using EIIS.Infrastructure.Model.Business;
using EIIS.Infrastructure.Model.System;
using EIIS.Presentation.Controllers.CommonSupport;
using EIIS.Presentation.Controllers.ViewModel;
using EIIS.Common.Jsons;
using EIIS.FrameWork.Attributes;
using EIIS.FrameWork.Cache;
using EIIS.Infrastructure.Model.System.Authority;

namespace EIIS.Presentation.Controllers.Business
{
    /// <summary>
    /// 包的控制器:包装部分
    /// </summary>
    [Description("器械包管理流程")]
    public partial class PackageController: BaseController
    {
        public IDictionaryManager DictionaryManager { get; set; }
        public IPackageManager PackageManager { get; set; }
        public ICache Cache { get; set; }

        [Description("包装管理页面")]
        [ViewPage]
        public ActionResult Index()
        {
            return View();
        }

        [Description("包装列表页面")]
        [ViewPage]
        public ActionResult List(string id)
        {
            return View();
        }

        [Description("新增包装")]
        [Function(ButtonID = "btnAdd")]
        public ActionResult Add()
        {
            this.ViewData["entity"] = new Package();
            return View();
        }

        [Description("修改包装")]
        [Function(ButtonID = "btnUpdate")]
        public ActionResult Edit(string id)
        {
            Package entity = PackageManager.Get(id);
            this.ViewData["entity"] = entity;
            return View();
        }

        [Description("删除包装")]
        [Function(ButtonID = "btnDelete")]
        public ActionResult Delete(IList<string> idList)
        {
            MessageInfo msg = new MessageInfo();
            msg.IsSuccess = true;
            msg.Message = "删除成功";
            PackageManager.Delete(idList.Cast<object>().ToList());
            return Json(msg);
        }

        [Description("保存包装")]
        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Save(Package entity)
        {
            MessageInfo msg = new MessageInfo();

            if (string.IsNullOrEmpty(entity.TiaoMH))
            {
                msg.IsSuccess = false;
                if (string.IsNullOrEmpty(entity.Id))
                    msg.Message = "新增失败，器械包条码不能为空";
                else msg.Message = "修改失败，器械包条码不能为空";
                return Json(msg);
            }
            else if (string.IsNullOrEmpty(entity.BaoMC))
            {
                msg.IsSuccess = false;
                if (string.IsNullOrEmpty(entity.Id))
                    msg.Message = "新增失败，包名称不能为空";
                else
                    msg.Message = "修改失败，包名称不能为空";
                return Json(msg);
            }
            else if (!HasBaoMC(entity.BaoMC))
            {
                msg.IsSuccess = false;
                if (string.IsNullOrEmpty(entity.Id))
                    msg.Message = "新增失败，该包不存在";
                else
                    msg.Message = "修改失败，该包不存在";
                return Json(msg);
            }
            else if (!HasQingXQGH(entity.QingXQGH))
            {
                msg.IsSuccess = false;
                if (string.IsNullOrEmpty(entity.Id))
                    msg.Message = "新增失败，该锅号不存在";
                else msg.Message = "修改失败，该锅号不存在";
                return Json(msg);
            }
            else if (!HasQingXQGC(entity.QingXQGC))
            {
                msg.IsSuccess = false;
                if (string.IsNullOrEmpty(entity.Id))
                    msg.Message = "新增失败，该锅次不存在";
                else msg.Message = "修改失败，该锅号不存在";
                return Json(msg);
            }
            
            if (string.IsNullOrEmpty(entity.Id))//新增
            {
                if (PackageManager.IsExistWithTiaoMH(entity.TiaoMH, "-1", ""))
                {
                    msg.IsSuccess = false;
                    msg.Message = "新增失败，已存在该条码号的记录";
                    return Json(msg);
                }

                if (Cache.GetSessionCache("HospUser") != null)
                {
                    HospUser user = (HospUser)Cache.GetSessionCache("HospUser");
                    entity.Id = Guid.NewGuid().ToString();
                    entity.BaoZSJ = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                    entity.BaoZR = user.Name;
                    entity.ZhuangT = 1;
                    PackageManager.Save(entity);
                }
                else
                {
                    msg.IsSuccess = false;
                    msg.Message = "新增失败，获取包装人失败";
                    return Json(msg);
                }                
            }
            else//修改
            {
                if (PackageManager.IsExistWithTiaoMH(entity.TiaoMH, entity.Id, ""))
                {
                    msg.IsSuccess = false;
                    msg.Message = "修改失败，已存在该条码号的记录";
                    return Json(msg);
                }
                var model = PackageManager.Get(entity.Id);
                model.TiaoMH = entity.TiaoMH;
                model.BaoMC = entity.BaoMC;
                model.QingXQGC = entity.QingXQGC;
                model.QingXQGH = entity.QingXQGH;
                PackageManager.Update(model);
            }

            msg.IsSuccess = true;
            msg.Message = "保存成功";
            return Json(msg, "text/html", JsonRequestBehavior.AllowGet);
        }

        /// <summary>
        /// 根据状态获取相应的包记录
        /// </summary>
        /// <param name="id">状态值</param>
        /// <param name="page">页码</param>
        /// <param name="rows">每页记录数</param>
        /// <param name="order">排序字段</param>
        /// <param name="sort">排序规则:asc,desc</param>
        /// <returns></returns>
        public ActionResult LoadAllByPage(string id, int page, int rows, string order, string sort)
        {
            long total = 0;
            IList<Package> ilist = GetPackages(id, page, rows, order, sort, out total);
            var list = ilist.Select(p => new {
                p.Id,
                p.BaoZR,
                p.TiaoMH,
                p.ZhuangT,
                BaoZRQ = DateTime.Parse(p.BaoZSJ).ToString("yyyy-MM-dd"),
                BaoZSJ = DateTime.Parse(p.BaoZSJ).ToString("HH:mm:ss"),
                BaoMC = DictionaryManager.Get(p.BaoMC) == null ? "" : DictionaryManager.Get(p.BaoMC).Name,
                QingXQGH = DictionaryManager.Get(p.QingXQGH) == null ? "" : DictionaryManager.Get(p.QingXQGH).Name,
                QingXQGC = DictionaryManager.Get(p.QingXQGC) == null ? "" : DictionaryManager.Get(p.QingXQGC).Name,
                BaoBH = p.BaoMC
            });
            list = list.OrderByDescending(p => p.BaoZRQ).ThenByDescending(p => p.BaoZSJ);
            return this.JsonFormat(new GridData { total = total, rows = list.ToList() });
        }       

        public ActionResult GetPackage(string id)
        {
            //包名称
            string strKeyword = Request["q"];
            IList<Dictionary> ilist = DictionaryManager.LoadAllByCategoryCode("baomc");            
            IEnumerable<Dictionary> query;
            if (!string.IsNullOrEmpty(strKeyword))
            {
                strKeyword = strKeyword.ToLower();
                query = ilist.Where(d =>
                {
                    {
                        string InputCode1 = string.IsNullOrEmpty(d.InputCode1) == true ? "" : d.InputCode1.ToLower();
                        string InputCode2 = string.IsNullOrEmpty(d.InputCode2) == true ? "" : d.InputCode2.ToLower();
                        string InputCode3 = string.IsNullOrEmpty(d.InputCode3) == true ? "" : d.InputCode3.ToLower();
                        return (d.Code.Contains(strKeyword)
                            || d.Name.Contains(strKeyword)
                            || InputCode1.Contains(strKeyword)
                            || InputCode2.Contains(strKeyword)
                            || InputCode2.Contains(strKeyword));
                    }
                });
            }
            else
            {
                query = ilist;
            }
            return this.JsonFormat(new GridData { total = query.LongCount(), rows = query.ToList() });
        }

        public ActionResult GetCleaningPotNo(string id)
        {
            //清洗器锅号
            IList<Dictionary> ilist = DictionaryManager.LoadAllByCategoryCode("qingxqgh");
            List<combobox_data> list = ilist.ToList().ConvertAll<combobox_data>(d => { return new combobox_data() { id = d.Id, text = d.Name, selected = (d.Id == id ? true : false) }; });
            return Json(list);
        }

        public ActionResult GetCleaningPotSer(string id)
        {
            //清洗器锅次
            IList<Dictionary> ilist = DictionaryManager.LoadAllByCategoryCode("qingxqgc");
            List<combobox_data> list = ilist.ToList().ConvertAll<combobox_data>(d => { return new combobox_data() { id = d.Id, text = d.Name, selected = (d.Id == id ? true : false) }; });
            return Json(list);
        }        

        public ActionResult CountByZhuangT(string id)
        {
            long count = PackageManager.CountByZhuangT(Convert.ToInt32(id));
            return this.JsonFormat(new { count = count });
        }

        private IList<Package> GetPackages(string id, int page, int rows, string order, string sort, out long total)
        {
            if (string.IsNullOrEmpty(sort))
            {
                switch (id)
                {
                    case "1": sort = "BaoZSJ"; break;
                    case "2": sort = "MieJSJ"; break;
                    case "20": sort = "MieJSJ"; break;
                    case "3": sort = "FaFSJ"; break;
                    case "30": sort = "FaFSJ"; break;
                    case "4": sort = "HuiSSJ"; break;
                    case "40": sort = "HuiSSJ"; break;
                }
                order = " desc ";
            }
            IList<Package> ilist = PackageManager.LoadAllByPage(out total, Convert.ToInt32(id), page, rows, order, sort);
            return ilist;
        }

        /// <summary>
        /// 根据编号效验包是否存在
        /// </summary>
        /// <param name="BaoMC">条目中包对应的ID号</param>
        /// <returns></returns>
        private bool HasBaoMC(string BaoMC)
        {
            var tempList = DictionaryManager.LoadAllByCategoryCode("baomc").Where(p => p.Id.ToLower() == BaoMC.ToLower());
            int count = tempList.Count();
            return count > 0;
        }

        /// <summary>
        /// 根据编号效验清洗器锅号是否存在
        /// </summary>
        /// <param name="QingXQGH">条目中清洗器锅号对应的ID号</param>
        /// <returns></returns>
        private bool HasQingXQGH(string QingXQGH)
        {
            var tempList = DictionaryManager.LoadAllByCategoryCode("qingxqgh").Where(p => p.Id.ToLower() == QingXQGH.ToLower());
            int count = tempList.Count();
            return count > 0;
        }

        /// <summary>
        /// 根据编号效验清洗器锅次是否存在
        /// </summary>
        /// <param name="QingXQGC">条目中清洗器锅次对应的ID号</param>
        /// <returns></returns>
        private bool HasQingXQGC(string QingXQGC)
        {
            var tempList = DictionaryManager.LoadAllByCategoryCode("qingxqgc").Where(p => p.Id.ToLower() == QingXQGC.ToLower());
            int count = tempList.Count();
            return count > 0;
        }
       
    }
}
